//
//  YZMModBankCardViewController.m
//  YZMicroStock
//
//  Created by Lv.Dongdong on 16/7/12.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMModBankCardViewController.h"
#import "YZMProvince.h"
#import "YZMCity.h"
#import "YZMBankCardModel.h"
#import "YZMSeparatorCell.h"
#import "YZClient.h"
#import "MBProgressHUD+Utils.h"
#import "YZMProvinceListViewController.h"
#import "YZMBranchListViewController.h"
#import "YZMBankCardListCell.h"
#import "YZMAlertView.h"
#import <BlocksKit/UIControl+BlocksKit.h>
#import <ColorUtils/ColorUtils.h>

static NSString *const sYZMBankCardHeadCellID = @"YZMBankCardHeadCellID";
static NSString *const sYZMBankCardUnitCellID = @"YZMBankCardUnitCellID";

@interface YZMModBankCardViewController()<UITableViewDelegate, UITableViewDataSource, YZMLocationChooseDelegate, YZMBranchChooseDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) YZMProvince *province;
@property (nonatomic, strong) YZMCity *city;
@property (nonatomic, strong) NSString *branch;
@property (nonatomic, strong) UIButton *submitBT;
@property (nonatomic, strong) UIButton *setDefaultBT;
@property (nonatomic, strong) UIButton *deleteBT;
@property (nonatomic, strong) YZMBankCardModel *bankCard;
@property (nonatomic, strong) NSIndexPath *index;

@end

@implementation YZMModBankCardViewController

- (void)viewDidLoad{
    
    [super viewDidLoad];
    self.title = @"修改银行卡";
    self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
    [self createObjects];
}

#pragma mark -- network

- (void)submitBankCardDetailModify{
    
    NSString *province;
    NSString *city;
    
    if (self.province) {
        province = self.province.name;
        city = self.city.name;
    }else{
        province = self.bankCard.province;
        city = self.bankCard.city;
    }
    
    MBProgressHUD *hud = [MBProgressHUD showProgressMessageManual:@"修改中"];
    [YZClient bc_modifyBankCardWithCardID:self.bankCard.cid andBankName:self.bankCard.bankName andProvince:province andCity:city andBranch:self.branch success:^(NSURLResponse *response, id responseObject) {
        
        [hud hide:NO];
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            //保存数据
            YZMBankCardModel *model = self.bankCard;
            model.province = province;
            model.city = city;
            model.branch = self.branch;
            NSMutableArray *array = [YZMUserServiceInstance.user.bankCardList mutableCopy];
            [array replaceObjectAtIndex:[array indexOfObject:self.bankCard] withObject:model];
            YZMUserServiceInstance.user.bankCardList = array;
            [YZMUserServiceInstance.user createEncoder];
            
            [YZMUserServiceInstance fetchUserBankCardInfo];
            [YZMHCMInstance popViewController:nil animated:YES];
            [MBProgressHUD showMessage:@"修改成功"];
            
        }else{
            [topModel showMessage];
        }
        
    } failure:^(NSError *error) {
        
        [hud hide:NO];
        [error yz_showMessage];
    }];
}

- (void)clickDeleteBankCard{
    
    YZMAlertView *alertView = [[YZMAlertView alloc] init];
    alertView.titleLabel.hidden = YES;
    alertView.contentLabel.text = @"确认删除银行卡?";
    alertView.contentLabel.numberOfLines = 0;
    alertView.contentLabel.textAlignment = NSTextAlignmentCenter;
    alertView.contentLabel.textColor = [YZMAppStyle colorForBlackText];
    alertView.contentLabel.font = [YZMAppStyle largeSizeBoldFont];
    __weak __typeof(&*self) weakSelf = self;
    alertView.confirmHandle = ^{
        
        [weakSelf deleteBankCard];
        return YES;
    };
    [alertView show];
    
}

- (void)deleteBankCard{
    
    MBProgressHUD *hud = [MBProgressHUD showProgressMessageManual:@"删除中"];
    [YZClient bc_deleteBankCardWithCardID:self.bankCard.cid success:^(NSURLResponse *response, id responseObject) {
        
        [hud hide:NO];
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            NSMutableArray *array = [YZMUserServiceInstance.user.bankCardList mutableCopy];
            [array removeObject:self.bankCard];
            YZMUserServiceInstance.user.bankCardList = array;
            [YZMUserServiceInstance.user createEncoder];
            [YZMUserServiceInstance fetchUserBankCardInfo];
            [YZMHCMInstance popViewController:nil animated:YES];
            [MBProgressHUD showMessage:@"删除成功"];
            
        }else{
            [topModel showMessage];
        }
        
    } failure:^(NSError *error) {
        
        [hud hide:NO];
        [error yz_showMessage];
    }];
}

- (void)setDefaultBankCard{
    
    MBProgressHUD *hud = [MBProgressHUD showProgressMessageManual:@"设置中"];
    [YZClient bc_setDefaultBankCardWithCardID:self.bankCard.cid success:^(NSURLResponse *response, id responseObject) {
        
        [hud hide:NO];
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            NSMutableArray *array = [NSMutableArray array];
            for (YZMBankCardModel *model in YZMUserServiceInstance.user.bankCardList) {
                
                if (model.cid == self.bankCard.cid) {
                    
                    model.defaultFlag = YES;
                    [array insertObject:model atIndex:0];
                }else{
                    
                    model.defaultFlag = NO;
                    [array addObject:model];
                }
            }
            
            YZMUserServiceInstance.user.bankCardList = array;
            [YZMUserServiceInstance.user createEncoder];
            
            [YZMUserServiceInstance fetchUserBankCardInfo];
            [YZMHCMInstance popViewController:nil animated:YES];
            [MBProgressHUD showMessage:@"设置成功"];
            
        }else{
            [topModel showMessage];
        }
        
    } failure:^(NSError *error) {
        
        [hud hide:NO];
        [error yz_showMessage];
    }];
}

#pragma mark -- delegate

- (void)provinceDidChoose:(YZMProvince *)province andCity:(YZMCity *)city{
    
    self.province = province;
    self.city = city;
    self.branch = nil;
    [self.tableView reloadData];
    self.submitBT.enabled = NO;
}

- (void)branchDidChoose:(NSString *)branch{
    
    self.branch = branch;
    [self.tableView reloadData];
    
    if (self.bankCard.isCompletion) {
        
        if ([self.province.name isEqualToString:self.bankCard.province] && [self.city.name isEqualToString:self.bankCard.city]) {
            
            self.submitBT.enabled = NO;
            return;
        }
    }
    
    self.submitBT.enabled = YES;
}

#pragma mark -- ui

- (void)createObjects{
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.tableView.backgroundColor = [YZMAppStyle appBackgroundColor];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView registerClass:[YZMBankCardListCell class] forCellReuseIdentifier:sYZMBankCardHeadCellID];
    [self.tableView registerClass:[YZMSeparatorCell class] forCellReuseIdentifier:sYZMBankCardUnitCellID];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make){
        
        make.edges.equalTo(self.view);
    }];
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 15)];
    self.tableView.tableHeaderView = headerView;
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 120)];
    self.tableView.tableFooterView = view;
    
    self.submitBT = [YZMAppStyle submitButton];
    [self.submitBT setTitle:@"确定" forState:UIControlStateNormal];
    [self.submitBT bk_addEventHandler:^(id sender) {
        
        [self submitBankCardDetailModify];
        
    } forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:self.submitBT];
    [self.submitBT mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(view).offset(15);
        make.right.equalTo(view).offset(-15);
        make.top.equalTo(view).offset(20);
    }];
    
    if (!self.bankCard.defaultFlag) {
        
        self.setDefaultBT = [UIButton new];
        [self.setDefaultBT.titleLabel setFont:[YZMAppStyle mediumSizeFont]];
        self.setDefaultBT.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [self.setDefaultBT setTitle:@"设为默认卡" forState:UIControlStateNormal];
        [self.setDefaultBT setTitleColor:[YZMAppStyle colorForBlueText] forState:UIControlStateNormal];
        [self.setDefaultBT bk_addEventHandler:^(id sender) {
            
            [self setDefaultBankCard];
            
        } forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:self.setDefaultBT];
        [self.setDefaultBT mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.submitBT);
            make.bottom.equalTo(view).offset(-10);
        }];
    }
    
    self.deleteBT = [UIButton new];
    self.deleteBT.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [self.deleteBT setTitle:@"删除银行卡" forState:UIControlStateNormal];
    [self.deleteBT setTitleColor:[YZMAppStyle colorForBlueText] forState:UIControlStateNormal];
    [self.deleteBT.titleLabel setFont:[YZMAppStyle mediumSizeFont]];
    [self.deleteBT bk_addEventHandler:^(id sender) {
        
        [self clickDeleteBankCard];
        
    } forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:self.deleteBT];
    [self.deleteBT mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.submitBT);
        make.bottom.equalTo(view).offset(-10);
    }];
}

#pragma mark -- UITableViewDataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
        YZMBankCardListCell *cell = [tableView dequeueReusableCellWithIdentifier:sYZMBankCardHeadCellID forIndexPath:indexPath];
        cell.indexPath = self.index;
        cell.item = self.bankCard;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }
    
    static NSString *identifier = @"BankCardListUnitCell";
    YZMSeparatorCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[YZMSeparatorCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.textColor = [YZMAppStyle colorForGrayText];
        cell.textLabel.font = [YZMAppStyle mediumSizeFont];
        cell.detailTextLabel.font = [YZMAppStyle mediumSizeFont];
        cell.rightMargin = 0.0;
    }
    
    switch (indexPath.row) {
        case 0:{
            cell.textLabel.text = @"开户名";
            cell.textLabel.textColor=[YZMAppStyle colorForWhite];
            cell.detailTextLabel.textColor = [YZMAppStyle colorForGrayText];
            NSString *name = YZMUserServiceInstance.user.detail.name;
            if (name.length > 0) {
                
                cell.detailTextLabel.text = [name formatName];
            }
        }
            break;
        case 1:{
            cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"left_arrow"]];
            cell.textLabel.text = @"省市";
            cell.textLabel.textColor=[YZMAppStyle colorForWhite];
            cell.detailTextLabel.textColor = [YZMAppStyle colorForGrayText];
            if (!self.bankCard.isCompletion && !self.province) {
                cell.detailTextLabel.text = @"开户行所在省市";
            }else{
                
                if (self.province && self.city) {
                    
                    cell.detailTextLabel.text = [self.province.name stringByAppendingFormat:@" %@",self.city.name];
                    
                }else{
                    
                    cell.detailTextLabel.text = [self.bankCard.province stringByAppendingFormat:@" %@",self.bankCard.city];
                }
//                cell.detailTextLabel.textColor = [YZMAppStyle colorForWhite];
                
            }
        }
            break;
        case 2:{
            cell.textLabel.text = @"支行";
            cell.textLabel.textColor=[YZMAppStyle colorForWhite];
            cell.detailTextLabel.textColor = [YZMAppStyle colorForGrayText];
            cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"left_arrow"]];
            if ( (self.province && self.branch.length == 0) || (!self.bankCard.isCompletion && !self.province)) {
                
                cell.detailTextLabel.text = @"所属支行";
                
            }else{
                
                if (self.branch.length > 0) {
                    
                    cell.detailTextLabel.text = self.branch;
                    
                }else{
                    
                    cell.detailTextLabel.text = self.bankCard.branch;
                }
//                cell.detailTextLabel.textColor = [YZMAppStyle colorForWhite];
            }
        }
            break;
        default:
            break;
    }
    YZMIndexCount indexCount;
    indexCount.index = indexPath.row?indexPath.row:1;
    indexCount.count = 3;
    cell.indexCount = indexCount;
    
    return cell;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 1) {
        
        return 3;
    }
    
    return 1;
}

#pragma mark -- UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
        return 110;
    }
    
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        
        return 0;
    }
    return 15;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    if (indexPath.row == 1) {
        
        [YZMHCMInstance pushViewControllerWithName:@"provinceList" andParams:@{@"delegate":self}];
        
    }else if(indexPath.row == 2){
        
        if (!self.province && !self.bankCard.isCompletion) {
            
            [MBProgressHUD showMessage:@"请先选择开户行所在省市"];
            return;
        }
        
        MBProgressHUD *hud = [MBProgressHUD showMessageManual:@"获取支行信息中"];
        
        NSString *province;
        NSString *city;
        
        if (self.province) {
            
            province = self.province.name;
            city = self.city.name;
            
        }else{
            
            province = self.bankCard.province;
            city = self.bankCard.city;
            
        }
        
        [YZClient bc_fetchBranchListWithBankName:self.bankCard.bankName andProvince:province andCity:city success:^(NSURLResponse *response, id responseObject) {
            
            [hud hide:NO];
            YZGeneralResultModel *topModel = responseObject;
            if (topModel.success) {
                
                [YZMHCMInstance pushViewControllerWithName:@"branchList" andParams:@{@"delegate":self,@"branchList":topModel.data}];
            }else{
                
                [topModel showMessage];
            }
            
        } failure:^(NSError *error) {
            
            [hud hide:NO];
            [error yz_showMessage];
        }];
    }
}


#pragma mark - manager

+ (instancetype)createWithParams: (NSDictionary *)params
{
    YZMModBankCardViewController *ctrl = [[self alloc] init];
    [ctrl updateWithParams: params];
    return ctrl;
}

- (void)updateWithParams: (NSDictionary *)params
{
    self.bankCard = params[@"bankCard"];
    self.index = params[@"indexPath"];
}


@end
